import request from '@/utils/request';
import { AxiosPromise } from 'axios';
import { MaterialVO, MaterialForm, MaterialQuery } from '@/api/ymxbh/material/types';

/**
 * 查询材料列表
 * @param query
 * @returns {*}
 */

export const listMaterial = (query?: MaterialQuery): AxiosPromise<MaterialVO[]> => {
  return request({
    url: '/ymxbh/material/list',
    method: 'get',
    params: query
  });
};

/**
 * 查询材料详细
 * @param id
 */
export const getMaterial = (id: string | number): AxiosPromise<MaterialVO> => {
  return request({
    url: '/ymxbh/material/' + id,
    method: 'get'
  });
};

/**
 * 新增材料
 * @param data
 */
export const addMaterial = (data: MaterialForm) => {
  return request({
    url: '/ymxbh/material',
    method: 'post',
    data: data
  });
};

/**
 * 修改材料
 * @param data
 */
export const updateMaterial = (data: MaterialForm) => {
  return request({
    url: '/ymxbh/material',
    method: 'put',
    data: data
  });
};

/**
 * 删除材料
 * @param id
 */
export const delMaterial = (id: string | number | Array<string | number>) => {
  return request({
    url: '/ymxbh/material/' + id,
    method: 'delete'
  });
};


/**
 * 批量下载材料压缩包
 * @param id 材料ID
 * @param fileName 下载的文件名
 */
export const downloadBatch = async (id: string | number, fileName: string = 'materials.zip') => {
  try {
    const response = await request({
      // url: `/ymxbh/material/downloadBatch/${id}`,
      url: `/ymxbh/shipment/downloadBatchZip/${id}`,
      method: 'get',
      responseType: 'blob'
    });
    
    console.log('完整响应:', response);
    
    // 直接从响应中获取数据
    const blobData = response.data || response;
    
    // 检查数据是否存在
    if (!blobData) {
      throw new Error('未收到任何数据');
    }
    
    // 创建 Blob 对象
    const blob = new Blob([blobData], { type: 'application/zip' });
    
    // 检查 Blob 是否有效
    if (blob.size === 0) {
      throw new Error('下载的文件为空');
    }
    
    // 获取文件名
    let finalFileName = fileName;
    if (response.headers) {
      const contentDisposition = response.headers['content-disposition'];
      if (contentDisposition) {
        const filenameMatch = contentDisposition.match(/filename="?([^"]+)"?/);
        if (filenameMatch && filenameMatch[1]) {
          finalFileName = decodeURIComponent(filenameMatch[1]);
        }
      }
    }
    
    // 创建下载链接
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', finalFileName);
    link.style.display = 'none';
    
    // 添加到 DOM 并触发点击
    document.body.appendChild(link);
    link.click();
    
    // 清理
    setTimeout(() => {
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
    }, 100);
    
    return '下载成功';
  } catch (error: any) {
    console.error('下载失败:', error);
    
    // 尝试解析错误响应
    if (error.response && error.response.data) {
      const errorBlob = new Blob([error.response.data]);
      const errorText = await errorBlob.text();
      console.error('错误响应内容:', errorText);
    }
    
    throw new Error(error.message || '下载失败');
  }
};